package com.ulic.customerManApplication.commonmodule.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.base.BaseDao;
import com.ulic.customerManApplication.commonmodule.bo.Activie;
import com.ulic.customerManApplication.commonmodule.dao.ActivieDao;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.usermodule.bo.UserActivie;
@Component("activieDao")
public class ActivieDaoImpl extends BaseDao implements ActivieDao {

	@Override
	public Activie getActivie(int oid) throws Exception {
		return (Activie)hibernateTemplate.get(Activie.class, oid);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Activie> getActivie() throws Exception {
		return hibernateTemplate.find("from Activie order by oid");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setUserActivie(String userid, int objectid) throws Exception {
		//删除原有状态
		String hql = "from UserActivie r where r.user = ?";
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query q = session.createQuery(hql);
		q.setParameter(0, userid);
		List<UserActivie> list =q.list();
		for (UserActivie usera : list) {
			hibernateTemplate.delete(usera);
		}
		//添加新的状态
		UserActivie ua = new UserActivie();
		ua.setObjectid(objectid);
		User user = (User)hibernateTemplate.load(User.class, userid);
		ua.setUser(user);
		hibernateTemplate.save(ua);
	}

	@SuppressWarnings("unchecked")
	@Override
	public int[] getUserActivie(String userid) throws Exception {
		String hql = "from UserActivie a where a.user = "+Integer.parseInt(userid);
		List<UserActivie> list = hibernateTemplate.find(hql);
		int[] objectids = new int[(list.size())];
		for (int i = 0; i < list.size(); i++) {
			objectids[i] = list.get(i).getObjectid();
		}
		return objectids;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isUserActivie(String userid) throws Exception {
		String hql = "from Activie a where a.oid in ( select ua.objectid from UserActivie ua where ua.user = "+Integer.parseInt(userid)+")";
		try {
			List<Activie> list = hibernateTemplate.find(hql);
			if(list.size()>0){
				Activie a = list.get(0);
				return "activie".equals(a.getCode());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
